<template>
  <div class="page-container">
    <!-- 个人信息卡片 -->
    <Card class="profile-card">
      <div class="profile-header">
        <div class="profile-avatar">
          <img :src="filePath" :alt="user.nickname">
        </div>
        
        <div class="profile-info">
          <div class="profile-top">
            <h2 class="nickname">{{ user.nickname }}</h2>
            <div class="action-buttons" v-if="isSelf">
              <Button type="primary" ghost @click="edit">
                <Icon type="md-create" />
                编辑资料
              </Button>
              <Button type="error" ghost @click="logout">
                <Icon type="md-log-out" />
                退出登录
              </Button>
            </div>
            <Button v-else 
                    :type="type" 
                    ghost 
                    class="follow-btn"
                    @click="follow">
              {{ followButtonText }}
            </Button>
          </div>

          <p class="phone">{{ user.phone }}</p>
          
          <div class="profile-stats">
            <div class="stat-item" @click="showFansList">
              <span class="stat-num">{{ fansCount }}</span>
              <span class="stat-label">粉丝</span>
            </div>
            <div class="stat-item" @click="showFollowList">
              <span class="stat-num">{{ followCount }}</span>
              <span class="stat-label">关注</span>
            </div>
            <div class="stat-item">
              <span class="stat-num">{{ likeCount }}</span>
              <span class="stat-label">获赞</span>
            </div>
          </div>
        </div>
      </div>
    </Card>

    <!-- 内容区域 -->
    <Card class="content-card">
      <div class="content-tabs">
        <div class="tab-group">
          <div class="tab-item" 
               :class="{ active: mode === 0 }"
               @click="mode = 0">
            我的帖子
          </div>
          <div class="tab-item"
               :class="{ active: mode === 1 }"
               @click="mode = 1">
            我的收藏
          </div>
        </div>
      </div>

      <div class="content-body">
        <!-- 我的帖子 -->
        <div v-show="mode === 0">
          <SXQFriendUpdateList 
            :callback="loadDataFriendUpdates" 
            :friend-list="friendList"
            :show-delete="isSelf"
            @delete-post="deletePost"
          />
        </div>

        <!-- 我的收藏 -->
        <div v-show="mode === 1">
          <SXQFriendUpdateList 
            :callback="loadCollection" 
            :friend-list="collectionList"
          />
        </div>
      </div>
    </Card>

    <!-- 编辑弹窗 -->
    <Modal v-model="editVisible"
           title="编辑个人资料"
           @on-ok="editSubmit">
      <div class="edit-form">
        <div class="form-item">
          <label>头像</label>
          <div class="avatar-upload">
            <img :src="filePath" class="preview-avatar">
            <Upload :before-upload="upload">
              <Button icon="ios-cloud-upload-outline">更换头像</Button>
            </Upload>
          </div>
        </div>
        
        <div class="form-item">
          <label>昵称</label>
          <Input v-model="editUser.nickname" placeholder="请输入昵称"/>
        </div>
        
        <div class="form-item">
          <label>手机</label>
          <Input v-model="editUser.phone" placeholder="请输入手机号"/>
        </div>
        
        <div class="form-item">
          <label>密码</label>
          <Input v-model="editUser.password" type="password" placeholder="请输入新密码"/>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  fileUpload,
  followListFollow, getCollectionFriendUpdate,
  getFriendUpdatesVOByUserId,
  getUser, getUserLikeCount,
  isFollow, logout,
  setUser,
  deleteFriendUpdate
} from "@/api/api";
import SXQFriendUpdateList from "@/components/SXQ-FriendUpdateList";

export default {
  name: "SettingPage",
  components: {SXQFriendUpdateList},
  computed: {
    // 是否为本人
    isSelf() {
      return this.targetUserId == JSON.parse(sessionStorage.getItem("user")).id
    }
  },
  data() {
    return {
      mode: 0,
      filePath: null,
      file: null,
      user: null,
      fansCount: 0,
      followCount: 0,
      followButtonText: "关注",
      type: "warning",
      editVisible: false,
      editUser: "",
      listItem: [
        {
          title: '帖子',
          type: 'ios-book',
          classiest: 'list-item active'
        },
        {
          title: '收藏',
          type: 'ios-star',
          classiest: 'list-item'
        },
        {
          title: '简介',
          type: 'md-person',
          classiest: 'list-item'
        }
      ],
      friendList: [],
      targetUserId: null,
      collectionList: [],
      likeCount: 0
    }
  },
  beforeMount() {
    this.targetUserId = this.$route.query.userId
  },
  mounted() {
    this.loadData()
    this.loadDataFriendUpdates()
    this.loadCollection()
    this.loadLikeCount()
  },

  methods: {
    logout() {
      logout().then(res => {
        if (res.body.code == 1) {
          sessionStorage.clear()
          this.$store.state.isLogin = null
          this.$router.push({
            path: "/"
          }, () => {}, () => {})
          this.$Message.success("已退出登录")
        }
      })
    },
    loadLikeCount() {
      getUserLikeCount(this.targetUserId).then(res => {
        if (res.body.code != 1) {
          this.$Message.error(res.body.msg)
          return
        }
        this.likeCount = res.body.data
      })
    },
    matchList(list) {
      // 构造临时集合
      let tempList = []
      list.forEach(it => {
        tempList.push({
          id: it.id,
          img: it.img,
          nums: [it['hitsCount'], it['likeCount'], it['commentCount'], it['collectCount'], it['shareCount']],
          content: it.content,
          title: it.title,
          createTime: it['createTime'],
          avatar: it['avatar'],
          nickname: it['nickname'],
          userId: it['userId']
        })
      })
      return tempList
    },
    loadCollection() {
      // 获得该用户收藏列表
      getCollectionFriendUpdate(this.targetUserId).then(res => {
        // 请求失败
        if (res.body.code != 1) {
          this.$Message.error(res.body.msg)
          return
        }
        // 刷新数据
        this.loadLikeCount()
        this.collectionList = this.matchList(res.body.data)
      })
    },
    loadDataFriendUpdates() {
      // 获得该用户发布列表
      getFriendUpdatesVOByUserId(this.targetUserId).then(res => {
        // 请求失败
        if (res.body.code != 1) {
          this.$Message.error(res.body.msg)
          return
        }

        // 渲染数据
        this.loadLikeCount()
        this.friendList = this.matchList(res.body.data)
      })
    },
    changeItem(index) {
      this.mode = index
      for (let i = 0; i < this.listItem.length; i++) {
        this.listItem[i].classiest = 'list-item'
      }
      this.listItem[index].classiest = 'list-item active'
    },
    edit() {
      this.editVisible = true
      this.editUser = {...this.user}
    },
    editSubmit() {
      setUser({
        id: this.user.id,
        phone: this.editUser.phone,
        nickname: this.editUser.nickname,
        password: this.editUser.password
      }).then(res => {
        if (res.body.code == 1) {
          this.$Message.success("修改成功")
        }
        this.loadData()
      })
    },
    loadData() {
      // 查询登录用户的关注列表中是否存在该用户
      isFollow(this.targetUserId).then(res => {
        if (res.body.code != 1) {
          this.$Message.error("服务器错误")
          return
        }

        this.followButtonText = res.body.data ? "已关注" : "关注"
        if (this.followButtonText === "已关注") {
          this.type = "primary"
        } else {
          this.type = "warning"
        }
      })

      // 该用户的信息
      getUser(this.targetUserId).then(res => {
        this.fansCount = res.body.data.fansCount
        this.followCount = res.body.data.followCount
        this.user = {...res.body.data}
        this.filePath = this.user.avatar
      })
    },
    follow() {
      followListFollow(this.targetUserId).then(res => {
        if (res.body.code != 1) {
          this.$Message.warning(res.body.msg)
        }
        this.loadData()
      })
    },
    showFollowList() {
      if (this.followCount == 0) {
        this.$Message.warning("无关注")
        return
      }

      this.$router.push({
        path: '/FollowListPage',
        query: {
          userId: this.targetUserId
        }
      }, () => {
      }, () => {
      })
    },
    showFansList() {
      if (this.fansCount == 0) {
        this.$Message.warning("无粉丝")
        return
      }

      this.$router.push({
        path: '/FansListPage',
        query: {
          userId: this.targetUserId
        }
      }, () => {
      }, () => {
      })
    },
    upload(file) {
      this.file = file
      let formData = new FormData();
      formData.append('file', this.file);

      fileUpload(formData).then(res => {
        if (res.body.code != 1) {
          this.$Message.error(res.body.msg)
          return
        }
        this.filePath = res.body.data
        setUser({
          id: JSON.parse(sessionStorage.getItem("user")).id,
          avatar: res.body.data
        })
      })
    },
    deletePost(postId) {
      this.$Modal.confirm({
        title: '确认删除',
        content: '确定要删除这篇帖子吗？删除后无法恢复。',
        onOk: () => {
          deleteFriendUpdate(postId).then(res => {
            if (res.body.code === 1) {
              this.$Message.success('删除成功');
              this.loadDataFriendUpdates(); // 重新加载列表
            } else {
              this.$Message.error(res.body.msg || '删除失败');
            }
          }).catch(() => {
            this.$Message.error('删除失败，请稍后重试');
          });
        }
      });
    }
  }
}
</script>

<style scoped>
.page-container {
  width: 75vw;
  margin: 20px auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.profile-card {
  background: white;
  border-radius: 10px;
  padding: 30px;
}

.profile-header {
  display: flex;
  gap: 30px;
}

.profile-avatar img {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
}

.profile-info {
  flex: 1;
}

.profile-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.nickname {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.phone {
  color: #666;
  margin-bottom: 20px;
}

.profile-stats {
  display: flex;
  gap: 40px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.stat-num {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.content-card {
  background: white;
  border-radius: 10px;
  padding: 0;
}

.content-tabs {
  padding: 20px 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.tab-group {
  display: flex;
  gap: 30px;
}

.tab-item {
  padding: 10px 0;
  cursor: pointer;
  color: #666;
  position: relative;
  font-size: 16px;
}

.tab-item.active {
  color: #2d8cf0;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background: #2d8cf0;
}

.content-body {
  padding: 20px;
}

.edit-form {
  padding: 10px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  color: #333;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}

.preview-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

/* 确保按钮图标垂直对齐 */
.ivu-icon {
  vertical-align: middle;
}
</style>